package com.kyh.util.html;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

public class HtmlUtil {
	
	/**
	 * @param urlnet 链接地址
	 * @param toRealPath 
	 * @param toFilename
	 */
	public static void urlToHtmlFile(String urlnet, String toRealPath, String toFilename) {
		try {
			InputStream inputStream;// 接收字节输入流
			InputStreamReader inputStreamReader;// 将字节输入流转换成字符输入流
			BufferedReader bufferedReader;// 为字符输入流加缓冲
			FileOutputStream fileOutputStream;// 字节输出流
			OutputStreamWriter outputStreamWriter;// 将字节输出流转换成字符输出流
			
			File toDir = new File(toRealPath);
			if (!toDir.exists()) {
				toDir.mkdirs();
			}

			URL url = new URL(urlnet);
			inputStream = url.openStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			bufferedReader = new BufferedReader(inputStreamReader);
			
//			int BUFFER_SIZE = 1024*1024*10;
//			char[] data = new char[BUFFER_SIZE];
//			int len = bufferedReader.read(data);
//			String s = String.valueOf(data, 0, len);
//			File toFile = new File(toRealPath + "/" + toFilename);
//			fileOutputStream = new FileOutputStream(toFile);
//			outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
//			outputStreamWriter.write(s);
			
//			Scanner scan = new Scanner(inputStream);
//			File toFile = new File(toRealPath + "/" + toFilename);
//			fileOutputStream = new FileOutputStream(toFile);
//			outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
//			while (scan.hasNextLine()) {
//				outputStreamWriter.write(scan.nextLine());
//			}
			
			String s;
			File toFile = new File(toRealPath + "/" + toFilename);
			fileOutputStream = new FileOutputStream(toFile);
			outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
			while ((s = bufferedReader.readLine()) != null) {
				outputStreamWriter.write(s);
			}

			outputStreamWriter.close();
			fileOutputStream.close();
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]) throws Exception {
		String urlnet = "http://www.baidu.com";
		String toRealpath = "E://tools/apache-tomcat-8.0.52_yjr/webapps/yjr_admin/t/templet";
		String toFilename = "test.html";
		urlToHtmlFile(urlnet, toRealpath, toFilename);
//		try {
//			URL url = new URL("http://www.baidu.com");
//			InputStream in = url.openStream();
//			InputStreamReader isr = new InputStreamReader(in);
//			BufferedReader bufr = new BufferedReader(isr);
//			String str;
//			while ((str = bufr.readLine()) != null) {
//				System.out.println(str);
//			}
//			bufr.close();
//			isr.close();
//			in.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}
}
